package org.apache.myfaces.blank.tm.frokjoin;

import org.apache.commons.lang3.time.StopWatch;
import org.apache.myfaces.blank.tm.ArrayUtils;

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

//import com.cz.mhm.forkjoin.sum.ArrayUtils;

/**
 * @author JsD
 * @ClassName ForkJoinTaskDemo02.java
 * @Description
 * @createTime 2021年06月03日 16:59:00
 */
public class ForkJoinTaskDemo02 {

    /**
     * 求和类
     */
    private static class SumTask  extends RecursiveTask<Integer> {

        // 以50为边界
        private static int THRESHOLD = 5000;

        private int[] src;
        private int fromIndex;
        private int toIndex;

        public SumTask(int[] src, Integer fromIndex, Integer toIndex) {
            this.src = src;
            this.fromIndex = fromIndex;
            this.toIndex = toIndex;
        }

        @Override
        protected Integer compute() {
            if((toIndex - fromIndex) < THRESHOLD) {
                int count = 0;
                for (int i=fromIndex; i<toIndex; i++) {
                    count = count + src[i];
                }

                return count;
            } else {
                int mid = (toIndex - fromIndex) / 2;
                SumTask leftTask = new SumTask(this.src, fromIndex, mid);
                SumTask rightTask = new SumTask(this.src, mid+1, toIndex);

                invokeAll(leftTask, rightTask);

                return  leftTask.join() + rightTask.join();
            }
        }

    }

    public static void main(String[] args) {
        int[] arr = ArrayUtils.getRandomCommonArrays(1000,1000000,100000);
        int count = 0;
        System.out.println("-----------------------使用FOR循环-----------------------");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i=0; i<arr.length; i++) {
            count = count + arr[i];
        }
        stopWatch.stop();
//      统计执行时间（秒）
        System.out.printf("执行时长：%d 秒.%n", stopWatch.getTime(TimeUnit.SECONDS));
//      统计执行时间（毫秒）
        System.out.printf("执行时长：%d 毫秒.%n", stopWatch.getTime(TimeUnit.MICROSECONDS));
//      统计执行时间（纳秒）
        System.out.printf("执行时长：%d 纳秒.%n", stopWatch.getTime(TimeUnit.NANOSECONDS));





        System.out.println("-----------------------使用ForkJoin-----------------------");
        StopWatch stopWatch2 = new StopWatch();
        stopWatch2.start();
        SumTask mytask = new SumTask(arr, 0, arr.length-1);
//        System.out.println();
        stopWatch2.stop();
//      统计执行时间（秒）
        System.out.printf("执行时长：%d 秒.%n", stopWatch2.getTime(TimeUnit.SECONDS));
//      统计执行时间（毫秒）
        System.out.printf("执行时长：%d 毫秒.%n", stopWatch2.getTime(TimeUnit.MICROSECONDS));
//      统计执行时间（纳秒）
        System.out.printf("执行时长：%d 纳秒.%n", stopWatch2.getTime(TimeUnit.NANOSECONDS));


//        // 创建随机数组成的数组:
//        long[] array = new long[400];
//        java.util.Arrays.fill(array,(long)(100*Math.random() + 60));

    }
}
